package com.gzhuxj201.controller;

import com.gzhuxj201.entity.*;
import com.gzhuxj201.service.AdminSevice;
import com.gzhuxj201.service.StudentService;
import com.gzhuxj201.service.TeacherService;
import com.gzhuxj201.service.SendEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private AdminSevice adminSevice;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;

    @Autowired
    private SendEmailService sendEmailService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping("/login/getCode")
    public Result getCode(@RequestBody FindPassword findPassword){
        String from="1552005509@qq.com";
        String to = findPassword.getEmail();
        String code= UUID.randomUUID().toString().substring(0,4);
        //发送验证码给指定邮件  //qq邮箱发送邮件授权码 wfnhljafnjhmbahc
        sendEmailService.sendEmail(from+"(广州大学-信息与计算科学-谢文健)",to,"验证码",code);
        //把验证码存储在redis中,并设置过期时间为60s
        String key="code:"+to;
        stringRedisTemplate.opsForValue().set(key,code,60L, TimeUnit.SECONDS);
        //把验证码存储在session中,等下验证
        //session.setAttribute("code",code);
        return Result.success(code);
    }



    @PostMapping("/login/updatePassword")
    public Result reSetPassword(@RequestBody FindPassword findPassword,HttpSession session){
        //从redis中获取验证码
        String key = "code:" + findPassword.getEmail();
        String serverCode = stringRedisTemplate.opsForValue().get(key);
        if(serverCode==null || serverCode.isEmpty()){
            return Result.error("验证码过期,请重新获取!");
        }
        //从session中获取生成的验证码
        //String  serverCode = (String) session.getAttribute("code");

        String email = findPassword.getEmail();
        String username = findPassword.getUsername();
        String code = findPassword.getCode();
        if(code==null){
            //未填写角色
            return Result.error("请选择role");
        }
        //0: 代表学生     1: 代表教师    2: 代表系统管理员
        Integer role = findPassword.getRole();
        if(role==0){
            Student student=studentService.selectByUsername(username);
            String studentEmail = student.getEmail();
            if(studentEmail!=null && studentEmail.equals(email) ){
                //邮箱与用户预留的邮箱相同
                if(serverCode.equals(code)){
                    //验证码正确,修改密码并且返回修改成功
                    Student updateStu = new Student();
                    updateStu.setPassword(findPassword.getPassword());
                    updateStu.setSno(student.getSno());
                    studentService.update(updateStu);
                    return Result.success("修改成功");
                }else {
                    return Result.error("验证码错误");
                }
            }else {
                return Result.error("用户名或邮箱错误");
            }
        }else if(role==1){
            Teacher teacher=teacherService.selectByUsername(username);
            String teacherEmail = teacher.getEmail();
            if(teacherEmail!=null && teacherEmail.equals(email) ){
                //邮箱与用户预留的邮箱相同
                if(serverCode.equals(code)){
                    //验证码正确,修改密码并且返回修改成功
                    Teacher updateTea = new Teacher();
                    updateTea.setPassword(findPassword.getPassword());
                    updateTea.setTno(teacher.getTno());
                    teacherService.update(updateTea);
                    return Result.success("修改成功");
                }else {
                    return Result.error("验证码错误");
                }
            }else {
                return Result.error("用户名或邮箱错误");
            }
        }else if(role==2){
            Admin admin=adminSevice.selectByUsername(username);
            String adminEmail = admin.getEmail();
            if(adminEmail!=null && adminEmail.equals(email) ){
                //邮箱与用户预留的邮箱相同
                if(serverCode.equals(code)){
                    //验证码正确,修改密码并且返回修改成功
                    Admin updateAdmin=new Admin();
                    updateAdmin.setPassword(findPassword.getPassword());
                    updateAdmin.setId(admin.getId());
                    int res= adminSevice.update(updateAdmin);
                    return Result.success("修改成功");
                }
            }else {
                return Result.error("用户名或邮箱错误");
            }
        }

        return Result.error("服务器忙");
    }



    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(String username, String password, Integer role, HttpSession session){
        log.info(username+"-"+password+"-"+role);
        if(role==2){
            Admin admin= adminSevice.login(username,password);
            if(admin!=null){
                session.setAttribute("user",admin);
                return Result.success(admin);
            }
        }
        else if(role==1){
            Teacher teacher= teacherService.login(username,password);
            if(teacher!=null){
                session.setAttribute("user",teacher);
                return Result.success(teacher);
            }
        }else if(role==0){
          Student student=studentService.login(username,password);
            if(student!=null){
                session.setAttribute("user",student);
                log.info("登录成功");
                log.info(student.getSno()+"-"+student.getUsername());
                return Result.success(student);
            }

        }

        return Result.error("不存在该用户");

    }


    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public Result logout(HttpSession session){
        session.removeAttribute("user");
        return Result.success();

    }
}
